<?php
namespace My\Controller;

use Utuo\BackgroundController;
use My\Model\MallOrderModel;
use My\Model\MallRateModel;
use Utuo\PHPExcel;
use Home\Logic\DistributionShopPayLogic;

class MallOrderController extends BackgroundController {
	
	private $deliverMethod = array(
		'0' => '物流',
		'1' => '无需配送',
	);
	
	/* 订单类型 */
	protected $orderTypes = array(
			0 => '待发货',
			1 => '交易成功',
			3 => '待买家签收',
			4 => '待卖家审核评价',
			5 => '待买家付款',
			6 => '退款订单',
			2 => '全部',
	);
	
	public function _initialize() {
		$this->setControllerTitle("订单管理");
		$this->setActionTitle(array(
			'index' => '订单列表',
			'deliver' => '发货',
			'detials' => '订单详细',
			'comment' => '评价',
			'showUserOrderList' => '用户分销的商品列表',
		));
		$this->setActionNav("index");
	}
	
	/**
	 * 获得查询参数
	 * @return $params
	 * array(
	 * 	 'agentId', // 代理id*
	 * 	 'type' // 类型 *
	 * 	 'tel' // 收货人电话
	 * 	 'consignee' // 收货人
	 * 	 'orderId' // 订单id
	 * )
	 */
	private function getParams() {
		$agentId = I('agentId', -1, "intval");
		$type = I("type", 0);
		$consignee = I("consignee");
		$orderId = I("orderId");
		$tel = I("tel");
		$params = array();
		
		/* 订单id */
		if ( !empty($orderId) ) {
			$params['orderId'] = $orderId;
		}
		
		/* 代理id(*)  */
		if ( $agentId*1 > 0 ) {
			$agent = M("MallAgent")->where("id=%d", $agentId)->find();
			if ( !$agent ) {
				$agentId = -1;
			}
		} elseif ( $agentId*1 === -1 ) {
			// 全部
		} elseif ( $agentId*1 === 0 ) { 
			// 总商家
		} else {
			$agentId = -1;
		}
		$params['agentId'] = $agentId;
		
		/* 类型(*) */
		if ( !in_array( $type, array_keys( $this->orderTypes ) ) ) {
			$type = 2;
		}
		$params['type'] = $type;
		
		/* 收货人电话  */
		if ( !empty($tel) ) {
			$params['tel'] = $tel;
		}
		
		/* 收货人  */
		if ( !empty($consignee) ) {
			$params['consignee'] = $consignee;
		}
		
		return $params;
	}
	
	/**
	 * 获得参数与查询条件
	 */
	private function getCondition( $params ) {
		$agentId = $params['agentId'];
		$type = $params['type'];
		$consignee = $params['consignee'];
		$orderId = $params['orderId'];
		$tel = $params['tel'];
		
		$condition = array( 'orders.cid' => $this->aid, );
		
		/** 筛选条件 */
		if ( !empty($orderId) ) {
			$condition['orders.order_id'] = $orderId;
		}
		
		if ( $agentId*1 >= 0 ) {
			 $condition['orders.agent_id'] = $agentId;
		}
		
		/* 类型 */
		if( $type == 0 ) { // 待发货
			$condition['orders.order_status'] = MallOrderModel::ORDER_STATUS_SHIPPING;
		} elseif ($type == 1) { // 交易成功
			$condition ['orders.order_status'] = MallOrderModel::ORDER_STATUS_COMPLETED;
		} elseif($type == 3) { // 待买家签收
			$condition ['orders.order_status'] = MallOrderModel::ORDER_STATUS_SIGN;
		} elseif($type == 4) { // 待卖家完成评价
			$condition ['orders.order_status'] = MallOrderModel::ORDER_STATUS_COMPLETED;
			$condition ['orders.rate_status'] = array('in', array(MallRateModel::RATE_STATUS_BUYER)); 
		} elseif($type == 5) { // 待买家付款
			$condition ['orders.order_status'] = MallOrderModel::ORDER_STATUS_PAY;
			$condition ['orders.pay_status'] = MallOrderModel::PAY_STATUS_NOT_PAID;
		} elseif($type == 6) {
			$condition ['orders.pay_status'] = MallOrderModel::PAY_STATUS_PAID;
			$condition ['orders.refund_status'] = 1;
		}
		
		/* 收货人电话  */
		if ( !empty($tel) ) {
			$condition['orders.tel'] = $tel;
		}
		
		/* 收货人  */
		if ( !empty($consignee) ) {
			$condition['orders.consignee'] = array('like', "%{$consignee}%");
		}
		
		return $condition;
	}
	
	/**
	 * 订单列表
	 */
	public function indexAction() {
		$belongs = array(
				'-1' => '全部',
				'0' => '总商家',
		);
		$this->setActionLink();
		$dso = D("MallOrder");
		$d = D("MallOrder orders");
		$params = $this->getParams();
		$condition = $this->getCondition($params);
		/* 查询  */
		$productOrderLists = $d->join("__WECHAT_USER__ user on user.id=orders.uid")->where($condition)->field("orders.*,user.nickname,user.openId")->limit($this->getPageSize())->page($this->getPage())->order("id desc")->select();
		$productOrderCount = $d->where($condition)->count();
		$dso->bindOrderDetail ( $productOrderLists, 0 );
		foreach ($productOrderLists as &$v) {
			$v["orderShowStatus"] = $dso->getOrderShowStatus($v);
			$this->getOperate($v);
		}
		if ( $params['agentId']*1 > 0 ) {
			$agent = M("MallAgent")->where("id=%d", $params['agentId'])->find() and $belongs[$agent['id']] = $agent['name'];
		}
		$this->assign("belongsOptions", $this->getOption($belongs, $params['agentId']));
		$this->assign("orderTypesOptions", $this->getOption($this->orderTypes, $params['type']));
		$this->assign("params", $params);
		$this->showPage($productOrderCount, $this->getPageSize(), $params);
		$this->assign("productOrderLists", $productOrderLists);
		$this->display();
	}
	
	/**
	 * 导出Excel
	 */
	public function exportXLSAction() {
		$type = I('type', 0, 'intval');
		$startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
		$endDate = I('endDate', 0, 'intval') or $endDate = time();
		$params = array(
				'type' => $type,
				'startDate' => $startDate,
				'endDate' => $endDate,
		);
		$productOrderGoodsLists = $this->search( $params );
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setCreator("微美风铃")
					->setLastModifiedBy("微美风铃")
					->setTitle("销售报表")
					->setSubject("销售报表")
					->setDescription("销售报表")
					->setKeywords("销售 报表")
					->setCategory("报表");
	
	
		/*设置标题*/
		$titles = array('订单编号','商品总计','订单运费','订单合计','收件人','地址','电话','下单时间','产品名称','数量','拍下价格','规格');
		$fields = array('order_id'=> array('type'=>'string'),
				'goods_amount'=> array('type'=>'string'),
				'shipping_fee' => array('type'=>'string'),
				'total' => array('type'=>'string'),
				'consignee' => array('type'=>'string'),
				'fullAddress' => array('type'=>'string'),
				'tel' => array('type'=>'string'),
				'create_time'=>array('type'=>'datetime', 'format' => 'Y/m/d H:i:s'),
				'product_name' => array('type'=>'string'),
				'product_number' => array('type'=>'string'),
				'product_price' => array('type'=>'string'),
				'product_attr' => array('type'=>'string'));
		$sheet0 = $objPHPExcel->setActiveSheetIndex(0);
		$rowNumber = 1;
		foreach ($titles as $k => $v) {
			$sheet0->setCellValue(chr(ord('A')+$k).$rowNumber, $v);
		}
		$rowNumber++;
		foreach ( $productOrderGoodsLists as $v ) {
			$fieldIndex = 0;
			foreach ( $fields as $k0 => $v0 ) {
				$cellName = chr(ord('A')+$fieldIndex++).$rowNumber;
				$sheet0->setCellValueExplicit($cellName, $this->getShowData($v[$k0], $v0), $this->getCellFormat($v[$k0]));
				//$sheet0->setCellValue(chr(ord('A')+$fieldIndex++).$rowNumber, $this->getShowData($v[$k0], $v0));
			}
			$rowNumber++;
		}
		$objPHPExcel->getActiveSheet()->setTitle(date('Y年m月d', time($startDate)).'至'.date('Y年m月d', time($endDate))."销售报表");
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="'.date("Ymdhis").'.xls"');
		header('Cache-Control: max-age=0');
		header('Cache-Control: max-age=1'); // IE9时
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
	}
	
	/**
	 * 查询
	 * @param unknown $params
	 * @return Ambigous <\Think\mixed, string, boolean, NULL, multitype:, mixed, object>
	 */
	private function search( $params ) {
		$params = $this->getParams();
		$condition = $this->getCondition($params);
		$result = D("MallOrder orders")->join('__MALL_ORDER_GOODS__ goods on orders.id=goods.order_id')
											->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
											->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
											->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
											->where( $condition )
											->field("orders.order_id,orders.goods_amount,orders.shipping_fee,orders.goods_amount+orders.shipping_fee as total,orders.create_time".
													",orders.consignee,concat(province.name,' ',city.name,' ', area.name,' ',orders.address) as fullAddress,orders.tel".
													",goods.product_name,goods.product_number,goods.product_price,goods.product_attr")
											->select();
		return $result;
	}
	
	// 发货
	public function deliverAction() {
		$d = D("MallOrder");
		$orderId = I("id", 0);
		$productOrder = $d->where(array(
							'cid' => $this->aid,
							'id' => $orderId,
						))->find();
		$this->assign("mallOrder", $productOrder);
		$this->display();
	}
	
	// 发货提交
	public function deliverPostAction() {
		$d = D("MallOrder");
		$orderId = I("id", 0, "intval");
		// 验证
		$order = $d->where(array( "cid" => $this->aid, "id" => $orderId))->find();
		$order or $this->ajaxError("订单不存在");
		$order['order_status'] == MallOrderModel::ORDER_STATUS_SIGN and $this->ajaxError("订单已发货");
		$d->field('deliver_method,express_name,shipping_no,deliverman_uid')->create();
		$data = array(
				'order_status' => MallOrderModel::ORDER_STATUS_SIGN,
				'shipping_time' => time(), );
		if( $d->deliver_method == 0 ) {
			$data['express_name'] = $d->express_name or $this->ajaxError("请选择快递名称.");
			$data['shipping_no'] = $d->shipping_no or $this->ajaxError("请填写物流单号.");
		} elseif( $d->deliver_method == 1 ) {
			// 无需配送
		} else {
			$this->ajaxError("没有您选择的配送方式");
		}
		$data['deliver_method'] = $d->deliver_method;
		// 更新产品销量
		$productSalesSummary = M("MallOrderGoods")->where(array(
									"order_id" => $orderId
								))->group("product_id")->field("product_id,sum(product_number) as totalName")->select();
		foreach ($productSalesSummary as $v) {
			M("MallOrderGoods")->where("id=%d", $v['product_id'])->setInc("saled_count", 1);
		}
		// 设置发货状态
		false !== $d->where(array( 'id' => $orderId, ))->save($data) and $this->ajaxSuccess("发货成功");
		$this->ajaxSuccess("发货失败");
	}
	
	// 订单评论
	public function commentAction() {
		$orderId = I('id');
		$productOrder = D( "MallOrder" )->getOrder($orderId, 0, $this->aid);
		$this->bindComment($productOrder);
		$this->assign("mallOrder", $productOrder);
		$this->display();
	}
	
	// 绑定评价内容
	public function bindComment( &$productOrder ) {
		$productRateLists = M("MallRate")->where(array('order_id' => $productOrder['id'], 'reviewer' => MallRateModel::REVIEWER_BUYER))->select();
		foreach ( $productOrder['orderItems'] as $productId => &$v ) {
			foreach ( $v['items'] as $k => &$item ) {
				foreach ( $productRateLists as $rate) {
					if ( $rate['product_id']==$productId and $rate['order_goods_id']==$item['orderGoodsId'] ) {
						$item['buyer_rate_content'] = $rate['content'];
						$item['buyer_rate_time'] = $rate['create_time'];
						$item['statusOptions'] = $this->getOption(MallRateModel::$rateCheckStatus, $rate['status']);
						break;
					}
				}
			}
		}
	}
	
	/**
	 * 卖家评价提交
	 *   格式:
	 * 		'order_id' => '订单id',
	 * 		'rates' => array('order_goods_id(订单商品编号)' => array(
	 *						 'content' => '评价内容',
	 *						),... ...);
	 
	public function commentPostAction() {
		$orderId = I('id') or $this->ajaxError('未知订单号');
		$rates = I('rates', array()) or $this->ajaxError('评论内容不能为空');
		$order =  D( "ProductOrder" )->getOrder($orderId, 0, $this->aid)  or $this->ajaxError("未找到订单");
		false === D("ProductRate")->submitRate($order, $rates, $this->aid, ProductRateModel::REVIEWER_SALLER) and $this->ajaxSuccess("评价失败");
		$this->ajaxSuccess("评价成功");
	}*/
	
	public function checkCommentPostAction() {
		$orderId = I('id') or $this->ajaxError('未知订单号');
		$rates = I('rates', array()) or $this->ajaxError('评论内容不能为空');
		$order =  D( "MallOrder" )->getOrder($orderId, 0, $this->aid)  or $this->ajaxError("未找到订单");
		false === D("MallRate")->checkRate( $order, $rates) and $this->ajaxSuccess("审核失败");
		$this->ajaxSuccess("审核成功");
	}
	
	/**
	 * 订单详细
	 */
	public function detialsAction() {
		$orderId = I("id", 0);
		$order = $this->getOrder($orderId);
		if ( in_array('deliver', $order['operates']) ) {
			$express = \Utuo\Express::getInstance();
			$expressNames = $express->getExpressname();
			$expressValues = array_values($expressNames);
			$order['deliverMethodRadio'] = $this->getRadio("deliver_method", $this->deliverMethod, '0');
			$order['expressOptions'] = $this->getOption(array_combine($expressValues, $expressValues), $order['express_name'], "====请选择快递====");
		}
		$this->assign("order", $order);
		$this->display();
	}
	
	/**
	 * 取消订单
	 */
	public function cancelOrderAction() {
		$orderId = I ( "id", 0, "int" );
		$d = M ( "MallOrder" );
		$d->where ( array (
				"cid" => $this->aid,
				"id" => $orderId,
				"order_status" => MallOrderModel::ORDER_STATUS_PAY,
				"pay_status" => MallOrderModel::PAY_STATUS_NOT_PAID,
		) )->setField ( "order_status", MallOrderModel::ORDER_STATUS_CANCELED ) and $this->ajaxSuccess ( "取消成功" );
		$this->ajaxError ( "取消失败" );
	}
	
	/**
	 * 确认已退款
	 */
	public function confirmRefundAction() {
		$orderId = I ( "id", 0, "int" ); // 订单id(*)
		$refundId = I ( "refundId", 0, "int" ); // 退款id
		$condition = array(
			'a.cid' => $this->aid,
			'a.id' => $orderId,
			'b.status' => 0,
		);
		$refundId and $condition['b.id'] = $refundId;
		$orderRefundList = M ( "MallOrder a" )->join("__MALL_REFUND__ b on a.order_id=b.orderNo")
													->where( $condition )
													->field("a.*,b.id as refundId,b.refundNo,b.refundTotalFee,b.all")
													->select();
		// 循环确认退款
		foreach ( $orderRefundList as $orderRefund ) {
			$error = 0;
			if ( $orderRefund['all']  ) { // 全款退款处理
				$data = array();
				$pay = \Utuo\Pay::getInstance($orderRefund['pay_method'], DistributionShopPayLogic::getApiConfig(array('paymentMethod' => $orderRefund['pay_method'],)));
				if ( $orderRefund['pay_method'] == 'WxTenpay'  ) {
					// 要更新的状态
					$data['order_status'] = MallOrderModel::ORDER_STATUS_REFUND_PROCESSING;
					$data['refund_status'] = 1;
					// 调用接口申请退款
					if ( false === $pay->refund(null, $orderRefund['refundNo'], $orderRefund['actual_cost'], $orderRefund['refundTotalFee'], array(
							'orderNo' => $orderRefund['order_id'],
					)) ) {
						$error = $pay->getError();
					}
				} else {
					// 要更新的状态
					$data['order_status'] = MallOrderModel::ORDER_STATUS_REFUND_SUCCESS;
					$data['pay_status'] = MallOrderModel::PAY_STATUS_REFUND;
					$data['refund_status'] = 2;
				}
				// 调用接口无误时更新
				if ( !$error ) {
					if ( false !== M("MallRefund")->where(array('id'=>$orderRefund['refundId'], 'status'=>0))->setField("status", 1) ) {
						if ( false !== M ( "MallOrder" )->where(array( 'id' => $orderRefund['id'] ))->save( $data ) ) {
							
						} else {
							$error = "退款订单状态更新失败";
						}
					} else {
						$error = "退款申请更新失败";
					}
				}
			}
			$error and $this->ajaxError("退款确认失败:".$error);
		}
		$this->ajaxSuccess("退款确认成功");
	}
	
	/**
	 * 获得指定用户的推广订单列表
	 */
	public function showUserOrderListAction() {
		$pageSize = $this->getPageSize();
		$p = $this->getPage();
		$uid = I('uid', 0, "intval");
		$m = M("MallOrderGoods goods")->join("__DISTRIBUTION_SHOP_ORDER__ orders on goods.order_id=orders.id", "LEFT")
											->where(array(
											 	'goods.reward_uids' => array("exp", "is not null and find_in_set({$uid},goods.reward_uids)"),
											 ));
		$n = clone $m;
		$count = $n->count();
		$orderGoodsLists = $m->field("goods.*,orders.order_id as orderNo")->limit($pageSize)->page($p)->select();
		$this->showPage($count, $pageSize);
		$this->assign("orderGoodsLists", $orderGoodsLists);
		$this->display();
	}
	
	private function setActionLink() {
		foreach ($this->orderTypes as $k => $v) {
			$this->setLinkNav("$v", U('MallOrder/index', array('type'=>$k)));
		}
	}
	
	// 获得订单操作
	private function getOperate( &$v ) {
		$operates = array();
		
		if ( $v['buy_method'] == MallOrderModel::BUY_METHOD_GIFTS ) { // 送礼订单
			if(($v['order_status'] == MallOrderModel::ORDER_STATUS_SHIPPING) and ($v['buy_status'] == MallOrderModel::BUY_METHOD_COQUETRY) ) {
				$operates[] = "deliver";
			}
		} elseif(($v['order_status'] == MallOrderModel::ORDER_STATUS_SHIPPING)) {
			$operates[] = "deliver";
		}
		
		if ( $v['order_status'] == MallOrderModel::ORDER_STATUS_REFUND_APPLY ) {
			$operates[] = "refund_apply";
		}
		
		if ( $v['order_status'] == MallOrderModel::ORDER_STATUS_REFUND_PROCESSING ) {
			$operates[] = "refund_search";
		}
			 
		if (  $v ['order_status'] == MallOrderModel::ORDER_STATUS_PAY and $v ['pay_status'] == MallOrderModel::PAY_STATUS_NOT_PAID ) {
			$operates[] = "cancel";
		}
		
		if($v['order_status'] == MallOrderModel::ORDER_STATUS_COMPLETED and in_array($v['rate_status'], array(MallRateModel::RATE_STATUS_UNRATE, MallRateModel::RATE_STATUS_BUYER))) {
			$operates[] = "check_comment";
		}
		
		$v['operates'] = $operates;
	}
	
	/**
	 * 获得一个订单
	 * @param unknown $id
	 * @return Ambigous <\Think\mixed, boolean, NULL, multitype:, unknown, mixed, string, object>
	 */
	private function getOrder( $id ) {
		$order = M ( "MallOrder orders" )->join( "__WECHAT_USER__ user on orders.uid=user.id", "LEFT")
					->join( "__AGENT__ agent on agent.id = orders.agent_id", "LEFT" )
					->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
					->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
					->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
					->field ( "orders.*,user.nickname as userName,province.name as provinceName, city.name as cityName, area.name as areaName, agent.name as agentName" )
					->where ( "orders.id=%d", $id )->find ();
		if ( !$order ) return null;
		$orders = array (
				&$order
		);
		$this->bindOrderDetail ( $orders );
		return $order;
	}
	
	/* 绑定订单详细 */
	private function bindOrderDetail(&$orderLists) {
		/* 关联订单商品 */
		$dProductOrder = D ( "My/MallOrder" );
		$mProductGoods = M ( "MallOrderGoods" );
		foreach ( $orderLists as &$v ) {
			/* 处理不同的购买状态 */
			if ( $v['buy_method'] == MallOrderModel::BUY_METHOD_GIFTS ) {
				$gifts = M("MallGifts gifts")->where ( "gifts.order_id = {$v['id']}" )->find();
				$v['buy_status'] = $gifts['buy_status'];
				$v['to_uid'] = $gifts['to_uid'];
			} elseif ( $v['buy_method'] == MallOrderModel::BUY_METHOD_COQUETRY ) {
				
			}
			// 绑定显示状态
			$v ["orderStatusName"] = $dProductOrder->getOrderShowStatus ( $v );
			// 获得操作
			$this->getOperate($v);
			// 绑定订单商品
			$orderGoods = $mProductGoods->where ( "order_id=%d", $v ['id'] )->select ();
			foreach ( $orderGoods as &$v0 ) {
				$v ['orderItems'] [$v0 ['product_id']] or $v ['orderItems'] [$v0 ['product_id']] = array (
						'productId' => $v0 ['product_id'],
						'productName' => $v0 ['product_name'],
						'items' => array ()
				);
				$v ['orderItems'] [$v0 ['product_id']] ['items'] [] = array (
						'productPic' => $v0 ['product_pic'],
						'productNumber' => $v0 ['product_number'],
						'productPrice' => $v0 ['product_price'],
						'productAttr' => $v0 ['product_attr']
				);
			}
		}
	}
	
	/**
	 * 获得单元格格式
	 * @param unknown $fieldCfg
	 * @return string
	 */
	private function getCellFormat( $fieldCfg ) {
		if( $fieldCfg['type'] == 'string' ) {
			return \PHPExcel_Cell_DataType::TYPE_STRING;
		}
		return \PHPExcel_Cell_DataType::TYPE_STRING;
	}
	
	
	/**
	 * 获得数据展示格式
	 * @param unknown $value
	 * @param unknown $fieldCfg
	 * @return string|unknown
	 */
	private function getShowData($value, $fieldCfg) {
		if( $fieldCfg['type'] == 'datetime' ) {
			return date( $fieldCfg['format'], $value);
		}
		return $value;
	}
	
}